package me.firstapp.service.shop.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.shop.Product;
import me.firstapp.module.shop.Sku;
import me.firstapp.repository.shop.ProductRepository;
import me.firstapp.repository.shop.SkuRepository;
import me.firstapp.service.shop.SkuService;

@Service
public class SkuServiceImpl implements SkuService {

	@Autowired
	private SkuRepository skuRepository;

	@Autowired
	private ProductRepository productRepository;

	@Override
	public Page<Sku> findSkuPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams, String sortParam,
			String sortType, Long apiClientId) {
		return skuRepository.findSkuPage(pageNo, pageSize, searchParams, sortParam, sortType, apiClientId);
	}

	@Override
	public Sku addSku(Long productId, String name, Long apiClientId) {
		if (productId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "商品id");
		}
		if (StrUtils.isNULL(name)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "屬性名");
		}
		Product product = productRepository.findProductById(productId, apiClientId);
		if (product == null) {
			throw new ServiceException(StatusHouse.PRODUCT_NOT_EXIST);
		}
		Sku sku = new Sku();
		sku.setProductId(productId);
		sku.setProductName(product.getName());
		sku.setName(name);
		sku.setApiClientId(apiClientId);
		skuRepository.save(sku);
		return sku;
	}

	@Override
	public Sku updateSku(Long skuId, String name, Long apiClientId) {
		if (skuId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "屬性id");
		}
		Sku sku = skuRepository.findById(skuId, apiClientId);
		if (sku == null) {
			throw new ServiceException(StatusHouse.SKU_NOT_FOUND);
		}
		if (StrUtils.isNotNULL(name)) {
			sku.setName(name);
		}
		skuRepository.update(sku);
		return sku;
	}

	@Override
	public void deleteSkus(String ids, Long apiClientId) {
		if (StrUtils.isNULL(ids)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "属性id");
		}
		if (!ids.contains(",")) {
			Sku sku = skuRepository.findById(Long.valueOf(ids), apiClientId);
			if (sku != null) {
				skuRepository.deleteById(Long.valueOf(ids));
			}
		} else {
			String[] _ids = ids.split(",");
			Long[] _ids_ = new Long[_ids.length];
			for (int i = 0; i < _ids.length; i++) {
				Sku sku = skuRepository.findById(Long.valueOf(_ids[i]), apiClientId);
				if (sku != null) {
					_ids_[i] = Long.valueOf(_ids[i]);
				}
			}
			if (_ids.length > 0) {
				skuRepository.delete(_ids_);
			}
		}
	}

}
